package com.base.conf;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.base.interceptor.LogRecordInterceptor;
import com.base.interceptor.LoginInterceptor;

@EnableWebMvc
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    
    @Autowired
    private LogRecordInterceptor logRecordInterceptor;
    
    /**
     * 添加拦截器
     */
    public void addInterceptors(InterceptorRegistry registry) {
        // 登录拦截器
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login/**", "/logout")
                .excludePathPatterns("/error/**")
                // .excludePathPatterns("/index/**")
                .excludePathPatterns("/js/**")
                .excludePathPatterns("/css/**")
                .excludePathPatterns("/images/**")
                .excludePathPatterns("/plugins/**");
        // 操作日志记录拦截器
        registry.addInterceptor(logRecordInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login/**", "/logout")
                .excludePathPatterns("/error/**")
                // .excludePathPatterns("/index/**")
                .excludePathPatterns("/js/**")
                .excludePathPatterns("/css/**")
                .excludePathPatterns("/images/**")
                .excludePathPatterns("/plugins/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
    
    /**
     * 设置是否允许跨域请求
     */
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")// 设置允许跨域的路径
                .allowedOrigins("*")// 设置允许跨域请求的域名
                .allowCredentials(true)// 是否允许证书 不再默认开启
                .allowedMethods("GET", "POST", "PUT", "DELETE")// 设置允许的方法
                .maxAge(3600);// 跨域允许时间
    }
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        WebMvcConfigurer.super.addViewControllers(registry);
    }
    
    @Bean
    @Primary
    public FilterRegistrationBean<WebSiteMeshFilter> siteMeshFilter() {
        FilterRegistrationBean<WebSiteMeshFilter> fitler = new FilterRegistrationBean<WebSiteMeshFilter>();
        WebSiteMeshFilter siteMeshFilter = new WebSiteMeshFilter();
        fitler.setFilter(siteMeshFilter);
        return fitler;
    }
    
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        fastJsonConfig.setSerializeFilters(new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                if (value == null) {
                    return null;
                }
                if (value instanceof Date) {
                    String val = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
                    if (val.indexOf("00:00:00") > -1) {
                        val = val.replaceAll("00:00:00", "").trim();
                    }
                    return val;
                }
                if (value instanceof Long) {// 解决long型精度丢失问题
                    return value.toString();
                }
                return value;
            }
            
        });
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
    
    /**
     * 添加@EnableWebMvc注解后，找不到静态资源路径
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        // swagger-ui页面
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
}
